package com.ambulance.project.biz.service.impl;

import com.ambulance.common.exception.CustomException;
import com.ambulance.common.utils.VerifyCodeUtils;
import com.ambulance.project.biz.entity.SysCache;
import com.ambulance.project.biz.mapper.SysCacheMapper;
import com.ambulance.project.biz.service.SysCacheService;
import com.ambulance.utils.CommonUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 系统缓存 服务实现类
 * </p>
 *
 * @author zr
 * @since 2020-05-23
 */
@Service(value = "sysCacheService")
public class SysCacheServiceImpl extends ServiceImpl<SysCacheMapper, SysCache> implements SysCacheService {


    @Override
    @Transactional
    public void sendCode(String phone) {
        //todo 校验手机号
        QueryWrapper<SysCache> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("verifyKey", phone).gt("c_time", LocalDateTime.now()).last("LIMIT 1");
        //校验是否已经存在未过期的验证码
        SysCache one = getOne(queryWrapper);
        if (!CommonUtils.checkNull(one)) {
            throw new CustomException("请稍后重试");
        }


        SysCache cache = new SysCache();
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //保存验证码
        cache.setIsCheck(0).setVerifyKey(phone).setCurrentTime(LocalDateTime.now().plusMinutes(2L)).setVerifyCode(verifyCode);
        save(cache);
    }

    @Override
    public SysCache getByPhone(String phone) {
        QueryWrapper<SysCache> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("verifyKey", phone).gt("c_time", LocalDateTime.now()).last("LIMIT 1");
        //校验是否已经存在未过期的验证码
        SysCache one = getOne(queryWrapper);
        if(CommonUtils.checkNull(one)){
            throw new CustomException("验证码不存在");
        }
        return one;
    }


}
